package org.zhangkun.jmsg.webserver.config;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.zhangkun.jmsg.webserver.inter.Servlet;

/**
 * 
 * 
 * Copyright (C), 2006-2010, ChengDu Lovo info. Co., Ltd. FileName:
 * LISServlets.java ���ౣ�����е�Servlet
 * 
 * @author zhangkun
 * @Date 2011-6-17
 * @version 1.00
 */
public class ServletConfig {

	public final static String SERVLETS_CONFIG_NAME = "servlets.xml";

	/**
	 * ��ǰ���е�Servlet
	 */
	private HashMap<String, Servlet> allServlet;

	public ServletConfig() {
	}

	/**
	 * ����һ��servlet
	 * 
	 * @param text
	 * @return
	 */
	private Servlet createSelvlet(String text) {
		// TODO Auto-generated method stub
		try {
			Class<?> c = Class.forName(text);
			return (Servlet) c.newInstance();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * �������·��ȡ��һ��Servlet�����ؿձ�ʾû��
	 * 
	 * @param path
	 * @return
	 */
	public Servlet getServlet(String path) {
		return allServlet.get(path);
	}

	public boolean loadConfig(InputStream inputStream) {
		// TODO Auto-generated method stub
		allServlet = new HashMap<String, Servlet>();
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(inputStream);
			Element rootElement = doc.getRootElement();
			Iterator<Element> allServlets = rootElement.elementIterator();
			while (allServlets.hasNext()) {
				Element servlet = allServlets.next();
				Servlet s = createSelvlet(servlet.element("class").getText());
				if (s != null)
					allServlet.put(servlet.element("path").getText(), s);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
